<template>
  <div class="details">
    <el-card>
      <el-tabs>
        <el-tab-pane label="登录账户设置">
          <el-form label-width="80px" :model="form" :rules="rules" ref="form">
            <el-form-item label="姓名:" prop="username">
              <el-input v-model="form.username"></el-input>
            </el-form-item>
            <el-form-item label="密码:" prop="password">
              <el-input v-model="form.password"></el-input>
            </el-form-item>
            <el-form-item class="btn">
              <el-button type="primary" @click="update">更新</el-button>
              <el-button type="text">取消</el-button>
            </el-form-item>
          </el-form>
        </el-tab-pane>
        <el-tab-pane label="个人详情" lazy>
          <component
            :is="'UserInfo'"
            :userInfo="initUser"
            @updateUserInfo="updateUserInfo"
          ></component>
        </el-tab-pane>
        <el-tab-pane label="岗位信息" lazy>
          <component :is="'JobItem'"></component>
        </el-tab-pane>
      </el-tabs>
    </el-card>
  </div>
</template>

<script>
import { sysUser, sysUserPut } from '@/api/user'
export default {
  components: {
    UserInfo: () => import('./components/userInfo.vue'),
    JobItem:()=>import('./components/jobInfo.vue')
  },
  data () {
    return {
      id: this.$route.params.id,
      form: {
        username: '',
        password: ''
      },
      rules: {
        username: [
          { required: true, message: '必填', trigger: 'change' },
          { min: 2, max: 6, message: '请输入2到6位用户名', trigger: 'change' }
        ],
        password: [{ required: true, message: '必填', trigger: 'change' }]
      },
      user: '',
      initUser: {}
    }
  },
  created () {
    this.getData()
  },
  methods: {
    async getData () {
      const res = await sysUser(this.id)
      console.log('个人用户信息', res)
      // 部门形势   手动添加数据
      res.data.formOfEmployment = res.data.formOfEmployment || 1
      this.user = res.data
      // 取消两边数据的关联 深拷贝
      this.initUser = JSON.parse(JSON.stringify(res.data))
      this.form.username = res.data.username
    },
    // 修改员工基本信息
    update () {
      this.$refs.form.validate(async result => {
        if (result) {
          await sysUserPut({
            ...this.user,
            ...this.form
          })
          this.$message.success('更新成功')
          // 更新另一边的数据
          this.initUser = {
            ...this.user,
            ...this.form
          }
          this.$router.push('/employees')
        }
      })
    },
    updateUserInfo () {
      this.user = JSON.parse(JSON.stringify(this.initUser))
      this.form.username = this.user.username
    }
  }
}
</script>

<style lang="scss" scoped>
.el-form {
  width: 500px;
  margin: 20px auto;
  .btn {
    text-align: center;
  }
}
</style>
